package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishService setmealDishService;


    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @Override
    public R addSetmeal(SetmealDto setmealDto) {
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        if(CollUtil.isEmpty(setmealDishes)){
            return R.error("菜品为空，请先选择菜品！");
        }
        //首先保存setmeal数据
        int insert = setmealMapper.insert(setmealDto);
        //其次保存套餐菜品数据setmeal—dish
        //先获取菜品

        Long setmealId = setmealDto.getId();
        //因为缺失了setmealId,补全
        for (SetmealDish setmealDish : setmealDishes) {
           setmealDish.setSetmealId(setmealId);
            setmealDishService.save(setmealDish);
        }
        return insert>0?R.success("保存套餐成功！"):R.error("保存套餐失败！");
    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */

    @Transactional
    public R delete(List<Long> ids) {
        //先写一个查询条件呗
        //Select * from setmeal where id in(1,2,3) and status=1;
        //思路：查询呗
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.in(Setmeal::getId,ids);
        qw.eq(Setmeal::getStatus,1);
        Integer count = setmealMapper.selectCount(qw);
        if(count>0){
            //不能删,抛出一个异常吧
            throw new CustomException("套餐正在售卖，不能删除！");
        }
        //等于0那就删除呗,先删除套餐表中的数据
       setmealMapper.deleteBatchIds(ids);
        //再删除setmealDish数据
        //delete from setmeal_dish where sealmeal_id in(ids);
        LambdaQueryWrapper<SetmealDish> qw2 = new LambdaQueryWrapper<>();
        qw2.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(qw2);
        return R.success("套餐删除成功！");
    }
}
